/**
 * 日常 用来放 node 代码
 * 最初的项目。
 */
'use strict';
const express = require('express')
const cookieParser = require('cookie-parser')
const cookieSession = require('cookie-session')
const bodyParser = require('body-parser')
const multer = require('multer')
const ejs = require('ejs')
const mysql = require('mysql')


const DB = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'cici'
})



const app = express()

app.use(cookieParser('sd2iuozxcjkl3we1'))
app.use(bodyParser.urlencoded({ extended: false }))


// session
let keys = [];
for (let i = 0; i < 10000; i++) {
    keys.push('keys_' + Math.random())
}
app.use(cookieSession({
    name: 'vx_si',
    keys: keys,
    maxAge: 24 * 3600 * 1000
}))



app.set('view engine', 'ejs')
app.set('views', './views')
app.use(express.static('./static'))


// -------------------------------------

app.get('/', (req, res, next) => {
    DB.query('SELECT * FROM banner', (err, banners) => {
        if (err) {
            console.log(err)
            res.status(500).send('database error').end()
            return
        }

        res.banners = banners
        next()
    })
})

app.get('/', (req, res, next) => {
    DB.query('SELECT title,summery FROM article', (err, articles) => {
        if (err) {
            console.log(err)
            res.status(500).send('database error').end()
            return
        }

        res.articles = articles
        next()
    })
})

app.get('/', (req, res) => {
    let banners = res.banners
    let articles = res.articles
    res.render('index', { banners, articles })
})



// -------------------------------------
app.listen(8800, function(error) {
    console.log('running 8800')
})
